package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatCheckedTextView;
import androidx.fragment.app.FragmentTransaction;

import com.cretin.www.cretinautoupdatelibrary.model.DownloadInfo;
import com.cretin.www.cretinautoupdatelibrary.utils.AppUpdateUtils;
import com.google.gson.Gson;
import com.mylhyl.circledialog.CircleDialog;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.Org;
import com.zahb.qadx.model.Upgrade;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.adapter.TrainTaskAdapter;
import com.zahb.qadx.ui.fragment.EnterpriseFragment;
import com.zahb.qadx.ui.view.CircleImageView;
import com.zahb.qadx.util.CleanDataUtils;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.PackageUtils;
import com.zahb.qadx.util.Tips;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by huwei.
 * Data 2020-09-29.
 * Time 17:15.
 * 设置
 */
public class SettingActivity extends BaseActivity {
    //设置标记  用哪个fragment
    int what = 0;
    @BindView(R.id.tv_belongs)
    TextView tvBelongs;
    @BindView(R.id.check_enterprise)
    TextView checkEnterprise;
    @BindView(R.id.rl_account_security)
    RelativeLayout rlAccountSecurity;
    @BindView(R.id.rl_customer_service)
    RelativeLayout rlCustomerService;
    @BindView(R.id.rl_user_agreement)
    RelativeLayout rlUserAgreement;
    @BindView(R.id.personNum_change)
    ImageView personNumChange;
    @BindView(R.id.rl_privacy_policy)
    RelativeLayout rlPrivacyPolicy;
    @BindView(R.id.rl_feedback)
    RelativeLayout rlFeedback;
    @BindView(R.id.rl_about)
    RelativeLayout rlAbout;
    @BindView(R.id.ll_according)
    LinearLayout llAccording;
    @BindView(R.id.fl_check)
    FrameLayout flCheck;
    @BindView(R.id.iv_icon)
    CircleImageView ivIcon;
    @BindView(R.id.tv_orgName)
    AppCompatCheckedTextView tvOrgName;
    String number;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tvCacheSize)
    TextView tvCacheSize;
    FragmentTransaction fragmentTransaction;
    @BindView(R.id.rlClearCache)
    RelativeLayout rlClearCache;
    @BindView(R.id.prompt)
    ImageView prompt;
    @BindView(R.id.version_name)
    TextView versionName;
    @BindView(R.id.app_version)
    RelativeLayout appVersion;

    @Override
    protected int getLayout() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        EnterpriseFragment buyFragment = new EnterpriseFragment();
        fragmentTransaction.add(R.id.fl_check, buyFragment).commit();
    }

    @Override
    protected void onResume() {
        List<Org> orgList = BaseApplication.getContext().getDataLogin().getOrgList();
        int currentOrg = BaseApplication.getContext().getDataLogin().getCurrentOrg();
        for (Org org : orgList) {
            if (org.getRootOrgId() == currentOrg) {
                tvOrgName.setText(org.getRootOrgName());
                ivIcon.setBackgroundResource(R.drawable.shape_white_oval);
                ImageLoaderKt.loadImageCircle(ivIcon, org.getOrgLogo(), R.mipmap.mine_icon);
            }
        }
        number = orgList.size() + "";
        //tvOrgName.setText(getIntent().getStringExtra("orgName"));
        //number = getIntent().getStringExtra("size");
        if ("1".equals(number)) {
            checkEnterprise.setVisibility(View.GONE);
        } else {
            checkEnterprise.setVisibility(View.VISIBLE);
        }

        tvCacheSize.setText(CleanDataUtils.getTotalSize(this, getExternalFilesDir(PdfActivity.dirType).getPath()));

        if (tvOrgName.getText().toString().equals("企安大学")){
            appVersion.setVisibility(View.VISIBLE);
            upgrade();
        }else {
            appVersion.setVisibility(View.GONE);
        }
        super.onResume();
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.system_setting;
    }

    @OnClick({R.id.tv_belongs, R.id.check_enterprise, R.id.rl_account_security, R.id.rl_customer_service, R.id.rl_user_agreement, R.id.personNum_change, R.id.rl_privacy_policy, R.id.rl_feedback, R.id.rl_about, R.id.ll_according, R.id.fl_check, R.id.rlClearCache})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.rl_customer_service: //客户服务

                break;

            case R.id.rl_feedback: //问题反馈
                String url3 = "https://www.wjx.cn/m/90352207.aspx?width=760&source=iframe";
                Log.e("MyWebViewActivity", "url: " + url3);
                MyWebViewActivity.actionStart(this, url3, "", 1);
                break;
            case R.id.rl_about: //关于我们
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;
            case R.id.tv_belongs:
                break;
            case R.id.check_enterprise:
                if (what == 0) {
                    fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    EnterpriseFragment deleteFragment = new EnterpriseFragment();
                    fragmentTransaction.replace(R.id.fl_check, deleteFragment);
                    what = 1;
                    llAccording.setVisibility(View.GONE);
                    flCheck.setVisibility(View.VISIBLE);
                    checkEnterprise.setText(getIntent().getStringExtra("phone"));
                    checkEnterprise.setVisibility(View.VISIBLE);
                    tvBelongs.setText("当前账号");
                    tvBelongs.setTextSize(16);
                    tvAccount.setVisibility(View.VISIBLE);
                    tvAccount.setText("你的账号加入了" + number + "个主企业");
                    Bundle bundle = new Bundle();
                    bundle.putString("size", String.valueOf(BaseApplication.getContext().getDataLogin().getOrgList().size()));
                    bundle.putString("phone", getIntent().getStringExtra("phone"));
                    bundle.putString("orgName", getIntent().getStringExtra("orgName"));
                    deleteFragment.setArguments(bundle);
                    fragmentTransaction.commit();
                }
//                else {
//                    EnterpriseFragment buyFragment = new EnterpriseFragment();
//                    fragmentTransaction.replace(R.id.fl_check, buyFragment);
//                    what = 0;
//                    checkEnterprise.setText("切换企业");
//                    llAccording.setVisibility(View.VISIBLE);
//                    flCheck.setVisibility(View.GONE);
//                    tvBelongs.setText("所属企业");
//                    tvBelongs.setTextSize(14);
//                    BToast.showText(SettingActivity.this,"点了0");
//                }
//                fragmentTransaction.commit();
                break;
            //账户安全
            case R.id.rl_account_security:
                intent = new Intent(SettingActivity.this, AccountSecurityActivity.class);
                intent.putExtra("phone", getIntent().getStringExtra("phone"));
                startActivity(intent);
                break;
            case R.id.rl_privacy_policy:
                String url = WebViewHelper.getBaseUrl() + "privacyAgreement?fromType=1&version=" + TrainTaskAdapter.getVersionCode(this);
                Log.e("MyWebViewActivity", "url: " + url);
                MyWebViewActivity.actionStart(this, url, "", 1);
                break;
            case R.id.rl_user_agreement:
                String url1 = WebViewHelper.getBaseUrl() + "userAgreement?fromType=1&version=" + TrainTaskAdapter.getVersionCode(this);
                Log.e("MyWebViewActivity", "url: " + url1);
                MyWebViewActivity.actionStart(this, url1, "", 1);
                break;
            case R.id.rlClearCache:

                new CircleDialog.Builder()
                        .setCanceledOnTouchOutside(false)
                        .setCancelable(false)
                        .setTitle("清除缓存")
                        .setText("系统将删除电子讲义缓存，清除后再次查看需要重新下载，是否删除？")
                        .setNegative("取消", null)
                        .setPositive("删除", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                CleanDataUtils.clearDir(getExternalFilesDir(PdfActivity.dirType).getPath());
                                tvCacheSize.setText(CleanDataUtils.getTotalSize(SettingActivity.this, getExternalFilesDir(PdfActivity.dirType).getPath()));
                            }
                        })
                        .show(getSupportFragmentManager());
                break;
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (what == 0) {
            super.onBackPressed();
        } else {
            EnterpriseFragment buyFragment = new EnterpriseFragment();
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fl_check, buyFragment);
            what = 0;
            checkEnterprise.setText("切换企业");
            llAccording.setVisibility(View.VISIBLE);
            flCheck.setVisibility(View.GONE);
            tvAccount.setVisibility(View.GONE);
            tvBelongs.setText("所属企业");
            tvBelongs.setTextSize(14);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (what == 0) {
                super.onBackPressed();
            } else {
                EnterpriseFragment buyFragment = new EnterpriseFragment();
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fl_check, buyFragment);
                what = 0;
                checkEnterprise.setText("切换企业");
                llAccording.setVisibility(View.VISIBLE);
                flCheck.setVisibility(View.GONE);
                tvAccount.setVisibility(View.GONE);
                tvBelongs.setText("所属企业");
                tvBelongs.setTextSize(14);
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

    }


    private void upgrade() {
        Map<String, Object> params = new HashMap<>();
        params.put("clientSystem", "2");
        Gson mGson = new Gson();
        String json = mGson.toJson(params);
        Log.e("json",json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .getUpgrade(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {

                    if (response.getStatusCode() == 200) {
                        if (response.getData()!=null){
                            Upgrade update=response.getData();
                            if (update.getVersionCode()>=PackageUtils.getVersionCode(SettingActivity.this)){
                                if (update.getVersionCode()>PackageUtils.getVersionCode(SettingActivity.this)){
                                    prompt.setVisibility(View.VISIBLE); //红点提醒有新版本
                                }
                                versionName.setText(update.getVersionName()); //显示接口返回版本
                                appVersion.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (update.getVersionCode()>=PackageUtils.getVersionCode(SettingActivity.this)){
                                            showBindToast("当前已是最新版本");
                                        }
                                    //更新
                                   update(update.getVersionCode(),update.getUpdateLog(),update.getVersionName(),update.getDownurl(),update.getIsForceUpdate());
                                    }
                                });
                            }
                        }else {
                                versionName.setText(PackageUtils.getVersionName(SettingActivity.this)); //获取本地版本
                        }

                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
//                    Tips.RequestError(getActivity());

                }));
    }
    /*
    downurl:下载地址
    versionCode:最新版本133
    isForceUpdate:1强制 0随意
    versionName:文字版本号v1.1.0
    updateLog:优化文案
     */
    private  void  update(int versionCode ,String updateLog, String versionName,String downurl,int isForceUpdate){

//        第二种方式，使用MODEL方式，组装好对应的MODEL，传入sdk中
        DownloadInfo info = new DownloadInfo().setApkUrl(downurl)
                .setProdVersionCode(versionCode)
                .setProdVersionName(versionName)
                .setMd5Check("68919BF998C29DA3F5BD2C0346281AC0")
                .setForceUpdateFlag(isForceUpdate)
                .setUpdateLog(updateLog);
        AppUpdateUtils.getInstance()
//                .addMd5CheckListener(...)//添加MD5检查更新
//                        .addAppDownloadListener(...)//添加文件下载监听
                .checkUpdate(info);
    }
}
